define(['moment'], function (moment) {
    return ['$scope', '$filter', '$stateParams', 'config', 'MMWService', '$datePicker', '$mdDialog',
        function ($scope, $filter, $stateParams, config, $MMWService, $datePicker, $mdDialog) {
            $scope.itemList = [];//列表
            var osNo = '';
            $scope.init = function () {
                $scope.mode = 'query';
                $scope.state = 0
                $scope.os_no = '';
                $scope.outcompany_no = '';
                $scope.printList = []; // 列印詳情
            };

            $scope.back = function () {
                if ($scope.mode == 'print') {
                    $scope.mode = 'preview';
                    document.getElementById('kmi-pdf-panel').src = '';
                } else {
                    $scope.$root.hideMenu();
                    $scope.$root.changeProgram('home', true);
                }
            };

            $scope.loadOutCompanyNo = function (callback) {
                $MMWService.showQueryListPNIG({
                    page_mode: 10,
                    condition: [
                        { name: $filter('translate')('B0236.queryList.column1_1'), column_name: 'SubcontractorNo', query_mode: '2', value: $scope.outcompany_no }
                    ],
                    header: [
                        { label: $filter('translate')('B0236.queryList.column1_1'), code: 'page_no' },
                        { label: $filter('translate')('B0236.queryList.column1_2'), code: 'page_name' }
                    ],
                    confirm: function (selectItem) {
                        if (callback) {
                            callback(selectItem);
                        } else {
                            $scope.outcompany_no = selectItem.page_no;
                        }
                    }
                });
            };

            $scope.loadOpNo = function (callback) {
                $MMWService.showQueryListPNIG({
                    page_mode: 'op_no_c',
                    condition: [
                        { name: $filter('translate')('B0236.queryList.column3_1'), column_name: 'A.OPNO', query_mode: '2', value: $scope.op_no }
                    ],
                    header: [
                        { label: $filter('translate')('B0236.queryList.column3_1'), code: 'page_no' },
                        { label: $filter('translate')('B0236.queryList.column3_2'), code: 'page_name' }
                    ],
                    confirm: function (selectItem) {
                        if (callback) {
                            callback(selectItem);
                        } else {
                            $scope.op_no = selectItem.page_no;
                        }
                    }
                });
            };

            $scope.loadOutSource = function () {
                $MMWService.showQueryListPNIG({
                    mode: 'M',
                    page_mode: 'os_no_c',
                    key: 'page_no',
                    selectKey: { key: 'is_select', true: 'true', false: 'false' },
                    pageRecord: 50,
                    //condition: [
                    //    { name: $filter('translate')('B0236.queryList.column2_1'), column_name: 'OSNO', query_mode: '2', value: $scope.os_no }
                    //],
                    header: [
                        { label: $filter('translate')('B0236.queryList.column2_1'), code: 'page_no' },
                        { label: $filter('translate')('B0236.queryList.column2_2'), code: 'page_name' }
                    ],
                    setCondition: function (conditions) {
                        if ($scope.state == 0) {
                            // 回货中
                            conditions.push({ column_name: 'STATUS', query_mode: '0', value: '1', merge_condition_model: 'and' });
                            //conditions.push({ column_name: 'STATUS', query_mode: '0', value: '11', merge_condition_model: 'and' });
                        } else if ($scope.state == 1) {
                            // 回货完
                            conditions.push({ column_name: 'STATUS', query_mode: '0', value: '11', merge_condition_model: 'and' });
                        } else if ($scope.state == 3) {
                            //20220704 modify wangzy for M#0114824: [松讚實業]外包單狀態為「部分回貨」沒有地方可補印外包單
                            // 部分回货
                            conditions.push({ column_name: 'STATUS', query_mode: '0', value: '10', merge_condition_model: 'and' });
                        } else if ($scope.state == 2) {
                            // 以上皆可
                            conditions.push({ column_name: 'STATUS', query_mode: '0', value: '1', merge_condition_model: 'and' });
                            conditions.push({ column_name: 'STATUS', query_mode: '0', value: '11', merge_condition_model: 'and' });
                            conditions.push({ column_name: 'STATUS', query_mode: '0', value: '10', merge_condition_model: 'and' });
                        };
                        return conditions;
                    },
                    selectCode: $scope.os_no,
                    confirm: function (selectItem) {
                        osNo = '';
                        selectItem.forEach(function (item) {
                            if (item.is_select == 'true') {
                                osNo += item.page_no + '|';
                            }
                        });
                        $scope.os_no = osNo.substr(0, osNo.length - 1);
                    }
                });
            };

            $scope.search = function () {
                //if ($scope.os_no == '' && $scope.outcompany_no == '') {
                //    $scope.$root.showAlert($filter('translate')('B0236.showAlert.column1'));
                //    return;
                //}
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_WIP.outsource_print_info_get',
                    content: {
                        state: $scope.state,//外包状态
                        os_no: $scope.os_no,//外包单号
                        outcompany_no: $scope.outcompany_no,//外包商
                        op_no: $scope.op_no//作业站编号
                    },
                    success: function (data) {
                        $scope.mode = 'list';
                        $scope.itemList = data.details;
                    },
                    error: function (data) {
                        $scope.$root.showAlert(data.Message);
                        $scope.mode = 'query';
                        $scope.itemList = [];
                    }
                });
                //} else {
                //    $scope.mode = 'query';
                //}
            };

            var selectNum = 0;
            $scope.isSelectAll = false;
            $scope.selectAll = function () {
                if ($scope.itemList.length > 0) {
                    $scope.isSelectAll = !$scope.isSelectAll;
                    $scope.itemList.forEach(function (item) {
                        item.isSelect = $scope.isSelectAll;
                    });
                    if ($scope.isSelectAll) {
                        selectNum = $scope.itemList.length;
                        $scope.mode = 'preview';
                    } else {
                        selectNum = 0;
                        $scope.mode = 'list';
                    }
                }
            };

            $scope.itemClick = function (index, item) {
                item.isSelect = !item.isSelect;
                if (item.isSelect) {
                    selectNum++;
                } else {
                    selectNum--;
                    $scope.isSelectAll = false;
                }

                if (selectNum <= 0) {
                    selectNum = 0;
                    $scope.mode = 'list';
                } else {
                    $scope.mode = 'preview';
                }
            };

            var pdf_url;
            $scope.preview = function () {
                var os_detail = [];
                $scope.itemList.forEach(function (item) {
                    if (item.isSelect) {
                        os_detail.push(item);
                    }
                });

                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_WIP.outsource_pdf_get',
                    content: {
                        os_detail: os_detail
                    },
                    success: function (data) {

                        for(var i = 0; i < os_detail.length; i++){
                            $scope.printList.push({
                                printNo: os_detail[i].os_no,
                                printType: '4' // 1: 流程卡打印 + 生產批開立; 3: 條碼標籤打印(補印); 4: 外包單 - 出貨打印; 5. 叫修作業;
                            });
                        }

                        pdf_url = data.outsource_pdf_get[0].url_pdf;
                        if (pdf_url.indexOf('http://') == -1) {
                            pdf_url = 'http://' + config.server.ip + ':' + config.server.port + pdf_url;
                        }
                        if (config.setting.outsidePDF == 'Y') {
                            var fs = window.nodeRequire('fs'), RuncardPath;
                            try {
                                // 20240321 modify by Alan for#159805 : electron升級後，兼容新舊版本
                                const remote = window.nodeRequire('electron').remote || window.nodeRequire('@electron/remote');
                                RuncardPath = remote.app.getAppPath();
                            } catch (e) {
                                RuncardPath = window.nodeRequire('path').dirname(process.execPath) + '\\package.nw';
                            }
                            RuncardPath += '\\www\\Runcard';
                            if (!fs.existsSync(RuncardPath)) {
                                fs.mkdirSync(RuncardPath);
                            }

                            // 20240222 add by Alan for#158151 : 清除Runcard目錄下未開啟的舊檔案
                            // 20240408 modify by Alan for#139948 : 改成同步讀取，避免刪除檔案後立即列印造成找不到檔案
                            fs.readdirSync(RuncardPath, (err, files) => {
                                if (err) {
                                    console.log(err);
                                }
                                //listing all files using forEach
                                files.forEach((file) => {
                                    // Do whatever you want to do with the file
                                    fs.unlink(RuncardPath + '/' + file, (err) => {
                                        if (err) {
                                            console.debug(err);
                                        }
                                    })
                                });
                            })

                            // 20240222 add by Alan for#158151 : 增加時間戳記，避免檔名重複造成檔案開啟時無法寫入
                            let pdfPath = `${RuncardPath}/RuncardPreview_${Date.now()}.pdf`;
                            $scope.$root.downloadFile(pdf_url, pdfPath, function (dist_path) {
                                try {
                                    window.nodeRequire('electron').shell.openItem(dist_path);
                                } catch (error) {
                                    nw.Shell.openItem(dist_path);
                                }
                            });
                        } else {
                            showPDFViewer(pdf_url);
                        }
                    }
                });
            };

            function showPDFViewer(pdf_url) {
                try {
                    window.nodeRequire('nw.gui').Window.open(pdf_url, {
                        title: 'PDF Viewer',
                        show: false,
                        icon: 'icon/icon.png',
                        focus: true
                    }, function (win) {
                        win.on('loaded', function () {
                            win.show();
                            win.print();
                        });
                    });
                } catch (e) {
                    $scope.mode = 'print';
                    document.getElementById('kmi-pdf-panel').src = 'JSplugins/pdfjs/web/viewer.html?file=' + pdf_url + '&openfile=false&viewbookmark=false&printfile=false&download=false#zoom=page-width';
                }
            }

            //M#53071: 調整列印的方式，解決列印模糊的問題
            $scope.print = function () {
                if (window.nodeRequire) {
                    var sumatraPDF = window.nodeRequire('sumatra-pdf');
                    if (sumatraPDF) {
                        var fs = window.nodeRequire('fs'), RuncardPath;
                        try {
                            // 20240321 modify by Alan for#159805 : electron升級後，兼容新舊版本
                            const remote = window.nodeRequire('electron').remote || window.nodeRequire('@electron/remote');
                            RuncardPath = remote.app.getAppPath();
                        } catch (e) {
                            RuncardPath = window.nodeRequire('path').dirname(process.execPath) + '\\package.nw';
                        }
                        RuncardPath += '\\www\\Runcard';
                        if (!fs.existsSync(RuncardPath)) {
                            fs.mkdirSync(RuncardPath);
                        }

                        // 20240222 add by Alan for#158151 : 清除Runcard目錄下未開啟的舊檔案
                        // 20240408 modify by Alan for#139948 : 改成同步讀取，避免刪除檔案後立即列印造成找不到檔案
                        fs.readdirSync(RuncardPath, (err, files) => {
                            if (err) {
                                console.log(err);
                            }
                            //listing all files using forEach
                            files.forEach((file) => {
                                // Do whatever you want to do with the file
                                fs.unlink(RuncardPath + '/' + file, (err) => {
                                    if (err) {
                                        console.debug(err);
                                    }
                                })
                            });
                        })

                        // 20240222 add by Alan for#158151 : 增加時間戳記，避免檔名重複造成檔案開啟時無法寫入
                        let pdfPath = `${RuncardPath}/RuncardPreview_${Date.now()}.pdf`;
                        $scope.$root.downloadFile(pdf_url, pdfPath, function (dist_path) {
                            $scope.$root.showLoading();
                            window.nodeRequire('sumatra-pdf').printWithSettings({
                                path: dist_path,
                                success: function () {
                                    printWiplogProcess(); // 列印完成後，需把列印詳情回送給後台做記錄
                                    $scope.$root.hideLoading();
                                    $scope.$root.showToast($filter('translate')('common.msg.success'));
                                },
                                error: function (error) {
                                    // 20201104 modify by WeiTing for M#77013 - 不清楚為何在實際列印後，有列印成一張紙或輸出成 PDF檔案時，都會執行 error區域，所以目前 error區域也先當列印完成後，把列印詳情回送給後台做記錄。
                                    printWiplogProcess(); // 列印完成後，需把列印詳情回送給後台做記錄
                                    $scope.$root.hideLoading();
                                    $scope.$root.showToast($filter('translate')('common.msg.success'));
                                    //console.error(error);
                                }
                            });
                        });
                    } else {
                        window.frames['kmi-pdf-panel'].pdf_print();
                    }
                } else {
                    window.frames['kmi-pdf-panel'].pdf_print();
                }
                /*
                if(config.setting.printSetting){
                    $PrintSetting.init({
                        callback:function(settings){
                            window.frames['kmi-pdf-panel'].pdf_print(settings);
                        }
                    });
                } else {
                    window.frames['kmi-pdf-panel'].pdf_print();
                }
                */
            };

            $scope.download = function () {
                window.frames['kmi-pdf-panel'].pdf_download();
            };

            $scope.cancel = function () {
                $scope.mode = 'preview';
                document.getElementById('kmi-pdf-panel').src = '';
                $scope.printList = [];
            };

            // 列印完成後，需把列印詳情回送給後台做記錄
            function printWiplogProcess(){
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_SN.print_wiplog_process',
                    content : {
                        printList: $scope.printList
                    },
                    success : function(){
                        $scope.printList = [];
                        $scope.search();
                    }
                });
            }
            
            // 列印詳情開窗查詢
            $scope.printInfoDialog = function(item){
                $mdDialog.dialog('module/moduleB/program/publicDialog/printInfoDialog.tmp.html',
                    function(dialog){
                        return {
                            printList: {
                                program: 'B0236',
                                repair_order_no: item.os_no,  // 維修單單號
                                print_user: '', // 列印人員
                                start_date: moment().subtract(3, 'days').format('YYYY-MM-DD'), // 開始日期
                                start_time: moment().subtract(3, 'days').format('HH:mm:ss'), // 開始時間
                                end_date: moment().endOf('day').format('YYYY-MM-DD'), // 結束日期
                                end_time: moment().endOf('day').format('HH:mm:ss'), // 結束時間
                                printDetailList: []
                            },
                            init: function(){ // 初始化
                                var start_dateTime = dialog.printList.start_date + ' ' + dialog.printList.start_time, // 開始日期 + 開始時間
                                    end_dateTime = dialog.printList.end_date + ' ' + dialog.printList.end_time; // 結束日期 + 結束時間

                                $MMWService.pageNumberInfoGet({
                                    page_mode : 'print_wiplot_info_get',
                                    query_condition_info : [
                                        {column_name: 'PRINTNO', query_mode:'2', value: '%' + dialog.printList.repair_order_no + '%', merge_condition_model:'AND'}, // 維修單單號
                                        {column_name: 'CREATOR', query_mode:'2', value: '%' + dialog.printList.print_user + '%', merge_condition_model:'AND'}, // 列印人員
                                        {column_name: 'CREATEDATE', query_mode:'4', value: start_dateTime, merge_condition_model:'AND'}, // 列印时间 - 開始
                                        {column_name: 'CREATEDATE', query_mode:'5', value: end_dateTime, merge_condition_model:'AND'}, // 列印时间 - 結束
                                        {column_name: 'PRINTTYPE', query_mode:'0', value: '4', merge_condition_model:'AND'} // 列印類型 - 1:批次流程卡; 2:系统出站标签; 3:末站标签打印; 4:外包单打印; 5:模具维修单打印;
                                    ]
                                }, function (response) {
                                    if(response && response.length > 0){
                                        dialog.printList.printDetailList = response;
                                    } else {
                                        dialog.printList.printDetailList = [];
                                        $scope.$root.showAlert($filter('translate')('common.msg.no_data'));
                                    }
                                });
                            },
                            back: function() {
                                dialog.hide();
                            },
                            search: function() { // 查詢
                                var start_dateTime = dialog.printList.start_date + ' ' + dialog.printList.start_time, // 開始日期 + 開始時間
                                    end_dateTime = dialog.printList.end_date + ' ' + dialog.printList.end_time; // 結束日期 + 結束時間

                                $MMWService.pageNumberInfoGet({
                                    page_mode : 'print_wiplot_info_get',
                                    query_condition_info : [
                                        {column_name: 'PRINTNO', query_mode:'2', value: '%' + dialog.printList.repair_order_no + '%', merge_condition_model:'AND'}, // 維修單單號
                                        {column_name: 'CREATOR', query_mode:'2', value: '%' + dialog.printList.print_user + '%', merge_condition_model:'AND'}, // 列印人員
                                        {column_name: 'CREATEDATE', query_mode:'4', value: start_dateTime, merge_condition_model:'AND'}, // 列印时间 - 開始
                                        {column_name: 'CREATEDATE', query_mode:'5', value: end_dateTime, merge_condition_model:'AND'}, // 列印时间 - 結束
                                        {column_name: 'PRINTTYPE', query_mode:'0', value: '4', merge_condition_model:'AND'} // 列印類型 - 1:批次流程卡; 2:系统出站标签; 3:末站标签打印; 4:外包单打印; 5:模具维修单打印;
                                    ]
                                }, function (response) {
                                    if(response && response.length > 0){
                                        dialog.printList.printDetailList = response;
                                    } else {
                                        dialog.printList.printDetailList = [];
                                        $scope.$root.showAlert($filter('translate')('common.msg.no_data'));
                                    }
                                });
                            },
                            changeStartDate: function() { // 更改開始日期
                                $datePicker.open(dialog.printList.start_date,
                                    function(dialogType){
                                        if(moment(dialogType.datePacker.pickDate).isBefore(dialog.printList.end_date)
                                        || moment(dialogType.datePacker.pickDate).isSame(dialog.printList.end_date))
                                        {
                                            dialog.printList.start_date = moment(dialogType.datePacker.pickDate).format('YYYY-MM-DD');
                                            dialogType.hide();
                                        }  
                                        else 
                                            $scope.$root.showAlert($filter('translate')('printInfoDialog.showAlert.column01')); // 開始日期不能大於結束日期！
                                    },
                                    function(dialogType){
                                        dialogType.hide();
                                    },{}
                                );
                            },
                            changeEndDate: function() { // 更改結束日期
                                $datePicker.open(dialog.printList.end_date,
                                    function(dialogType){
                                        if(moment(dialogType.datePacker.pickDate).isAfter(dialog.printList.start_date)
                                        || moment(dialogType.datePacker.pickDate).isSame(dialog.printList.start_date))
                                        {
                                            dialog.printList.end_date = moment(dialogType.datePacker.pickDate).format('YYYY-MM-DD');
                                            dialogType.hide();
                                        }  
                                        else
                                            $scope.$root.showAlert($filter('translate')('printInfoDialog.showAlert.column02')); // 結束日期不能小於開始日期！
                                    },
                                    function(dialogType){
                                        dialogType.hide();
                                    },{}
                                );
                            }
                        }
                    }
                );
            };

        }
    ];
});
